const _ = require("lodash");

function select32NumbersByS10(temp) {
  const allNumbers = Array.from({ length: 49 }, (_, i) =>
    (i + 1).toString().padStart(2, "0")
  );

  const streakMap = {};
  allNumbers.forEach((num) => {
    streakMap[num] = { maxWrong: 0, currentWrong: 0 };
  });

  // 🧠 统计每个号的“最大连续不中”
  temp.forEach((draw) => {
    const actual = draw.number;
    allNumbers.forEach((num) => {
      if (num === actual) {
        streakMap[num].maxWrong = Math.max(streakMap[num].maxWrong, streakMap[num].currentWrong);
        streakMap[num].currentWrong = 0;
      } else {
        streakMap[num].currentWrong += 1;
      }
    });
  });

  // 更新尾部遗漏
  allNumbers.forEach((num) => {
    streakMap[num].maxWrong = Math.max(streakMap[num].maxWrong, streakMap[num].currentWrong);
  });

  // ❌ 剔除历史中“最大连续错 ≥ 4”的号
  const safeNumbers = allNumbers.filter((num) => streakMap[num].maxWrong <= 3);

  // ✅ 从 safeNumbers 中按近期出现频率排序
  const freqMap = _.countBy(temp.map((v) => v.number));
  const sorted = safeNumbers
    .sort((a, b) => (freqMap[b] || 0) - (freqMap[a] || 0))
    .slice(0, 32);

  // ✨ 不足补冷却期短的号码
  if (sorted.length < 32) {
    const recentMap = {};
    for (let i = temp.length - 1; i >= 0; i--) {
      const num = temp[i].number;
      if (!recentMap[num]) {
        recentMap[num] = i;
      }
    }
    const backup = allNumbers
      .filter((num) => !sorted.includes(num) && streakMap[num].maxWrong <= 3)
      .sort((a, b) => (recentMap[a] || 9999) - (recentMap[b] || 9999))
      .slice(0, 32 - sorted.length);

    return sorted.concat(backup);
  }

  return sorted;
}

module.exports = select32NumbersByS10;
